<template>
  <div style="margin: 20px 0;" class="btn_box">
    <el-button type="primary" @click="handlerAdd">添加用户</el-button>
  </div>
  <div>
    <el-table :data="users" style="width: 100%;height: 500px;">
      <el-table-column label="序号" type="index" width="180"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="电话号码" prop="phone"></el-table-column>
      <el-table-column label="创建时间" prop="create_time" :formatter="resetDate"></el-table-column>
      <el-table-column label="所属角色" prop="role_id" :formatter="formatRole"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row._id)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />


    <el-dialog v-model="userFormVisible" title="添加用户" width="500px">
      <el-form :model="user" ref="userFormRef" lable-width="100px" lable-position="right" style="width: 400px; "
        :rules="rules">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" />
        </el-form-item>

        <el-form-item label="所属角色" prop="role_id">
          <el-select v-model="user.role_id" placeholder="请点击选择">
            <el-option v-for="option in roleOptions" :key="option._id" :label="option.name" :value="option._id" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="user.phone" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="user._id == null ?addData(userFormRef):updateData(userFormRef)"  >
            确定
          </el-button>
          <el-button @click=" userFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import type { roleInforDate } from '@/api/role/type';
import type { userInfoData } from '@/api/user/type';
import useRoleStore from '@/store/modules/role';
import { formateDate } from '@/utils/dataUtils';
import { nextTick, onMounted, reactive, ref } from 'vue';
import useUserStore from '@/store/modules/user';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
const userStore = useUserStore()
// 引入角色小仓库
const roleStore = useRoleStore()
const users = ref<userInfoData[] | undefined>([])
const handleEdit = (_id: string) => {
  handlerAdd()
  userStore.getUserById(_id).then(Response=>{
    // @ts-ignore
    user.value = Response
  })
}
const handleDelete = (_id: string) => {
    ElMessageBox.confirm(
      '确定要删除此条数据吗？',
       'Warning', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    cancelButtonText:'取消',
    type:"warning"  
   })
   .then(()=>{
    userStore.deleteUser(_id).then(()=>{
      ElMessage({
        type:"success",
        message:"删除成功",
      });
      getUserList()
    })
    .catch(()=>{})
   })
   
   
    }

// 角色列表
const roleOptions = ref<roleInforDate[] | undefined>([])
// 获取角色列表
const getRoleList = () => {
  roleStore.getRoleList().then(() => {
    roleOptions.value = roleStore.roles
  })
}
// 格式化角色名称方法
const formatRole = (_row: any, _colum: any, cellValue: string, _index: number) => {
  let role = roleOptions.value?.find(item => item._id == cellValue)
  return role?.name
}
// 格式化日期数据 :row:当前要格式化数据所在行对象，colum：列对象，cellvalue：要格式化的数据
const resetDate = (_row: any, _colum: any, cellValue: number, _index: number) => {
  return formateDate(cellValue)
}
// 当前页面
const currentPage = ref(1)
// 一页显示多少条数据
const pageSize = ref(5)
// 总条数
const total = ref(0)

const handleSizeChange = (val: number) => {
  pageSize.value = val
 getUserList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
 getUserList()
}
// 获取用户列表
const getUserList = () => {
  userStore.getUserList({ page: currentPage.value, size: pageSize.value }).then(Response => {
    users.value = userStore.users
    total.value = (Response?.total as number)
  })
}
// 自定义校验规则

const ValidateUsername = (_rules: any, value: any, callback: any) => {
  value = value.trim();
  // 获取输入长度
  const length = value && value.length;
  // 正则表达式
  const reg = /^[a-zA-Z0-9_]+$/;
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else if (length < 4 || length > 12) {
    callback(new Error("长度在4-12间"));
  } else if (!reg.test(value)) {
    callback(new Error("用户名只能由英文，数字或者下划线组成"));
  } else {
    callback();
  }
}
const ValidatePhone = (_rules: any, value: any, callback: any) => {
  value = value.trim();

  // 正则表达式
  const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  if (value === "") {
    callback(new Error("请输入电话号码"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入正确的电话号码"));
  } else {
    callback();
  }
}
const user = ref<userInfoData>({
  _id: null,
  name: '',
  username: '',
  password: '',
  phone: '',
  role_id: ''
})
// 添加弹窗是否展示
const userFormVisible = ref(false)
// 表单元素对象，需要和el-from的ref属性值相同
const userFormRef = ref<FormInstance>()
// 表单校验规则
const rules = reactive<FormRules>({
  username: [
    {
      required: true,
      validator: ValidateUsername,
      trigger: ['blur', 'change']
    },

  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
  ],
  role_id: [
    {
      required: true,
      message: '请选择角色',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      validator: ValidatePhone,
      trigger: 'blur',
    },
  ],
})
 const handlerAdd=()=>{
        //每次弹窗显示之前先初始化一下user对象，防止编辑过后user对象内一直存储信息，_id不再为null，无法进行添加操作
        user.value={
            _id:null,
            username:'',
            password:'',
            name:'',
            phone:'',
            role_id:''
        }
        userFormVisible.value=true
        //清空表单数据
        nextTick(()=>{
            //@ts-ignore
            userFormRef.value?.resetFields()
        })
    }
  const addData=(formEl:FormInstance|undefined)=>{
        if(!formEl) return
        formEl.validate(async (valid)=>{
            if(valid){
              userStore.addUser(user.value).then(()=>{
                userFormVisible.value=false;
                getUserList()
              })
            }else{
                console.log('error submit!');
                
            }
        })
    }
  const updateData=(formEl:FormInstance|undefined)=>{
        if(!formEl) return
        formEl.validate(async (valid)=>{
            if(valid){
              userStore.updateUser(user.value).then(()=>{
                userFormVisible.value=false;
                getUserList()
              })
            }else{
                console.log('error submit!');
                
            }
        })
    }

onMounted(() => {
  getRoleList()
  getUserList()
})
</script>

<style scoped></style>